package com.fjec.market.controller;

import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fjec.common.annotation.Json;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.SpecialMapUtil;
import com.fjec.market.entity.BizFollow;
import com.fjec.market.entity.InfoMarket;
import com.fjec.market.service.IBizFollowService;
import com.fjec.market.service.IInfoMarketService;
import com.fjec.market.view.MarketIndexVO;
import com.fjec.market.view.ShopVO;
import org.apache.commons.collections.MapUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.omg.CORBA.OBJECT_NOT_EXIST;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 001.市场表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2020-09-07
 */
@RestController
@RequestMapping("/")
public class InfoMarketController {

    @Autowired
    private IInfoMarketService infoMarketService;

    @Resource
    private IBizFollowService bizFollowService;

    // 查询市场列表
    @GetMapping("/n/market/getPage")
    public JsonResult getPage(Page page) {
        Map<String, Object> resultMap = infoMarketService.getMarkets(page);
        long total = MapUtils.getLongValue(resultMap, "total");
        return JsonResult.success()
                .data(resultMap)
                .total(total)
                .build();
    }

    // 查询市场详情
    @GetMapping("/n/market/getById")
    public JsonResult getMarketByCode(@RequestParam Integer markCode) {
        Map<String, Object> result = infoMarketService.getMarketByCode(markCode);
        return JsonResult.success().data(result).build();
    }

    @GetMapping("/n/market/getMyMarkets")
    public JsonResult getMyMarkets() {
        List<InfoMarket> markets = infoMarketService.getMarketsByBusiId(AccountInfo.getBusiId());
        return JsonResult.success().data(markets).build();
    }

    @GetMapping("/n/market/getAllMarketLocation")
    public JsonResult getAllMarketLocation() {
        List<Map<String, Object>> r = infoMarketService.getAllMarketLocation();
        return JsonResult.success().data(r).build();
    }

    @GetMapping("/n/market/getMarketLocation")
    public JsonResult getMarketLocation(Integer markCode) {
        Map<String, Object> result = infoMarketService.getMarketLocation(markCode);
        return JsonResult.success().data(result).build();
    }

    // 给定板块，查询拥有该板块的市场
    @GetMapping("/n/market/getMarketsHavingSection")
    public JsonResult getMarketsHavingSection(Integer sectionVal) {
        List<InfoMarket> result = infoMarketService.getMarketsHavingSection(sectionVal);
        return JsonResult.success().data(result).build();
    }

    // 按市场id和板块类型 查询商户列表
    @GetMapping("/n/section/getBusiness")
    public JsonResult getBusinessesOfMarketSection(Integer markCode, String sectionVal, Page page) {
        Map<String, Object> result = infoMarketService.getSectionBusinesses(markCode, Integer.parseInt(sectionVal), page);
        List<Map<String, Object>> shops = (List<Map<String, Object>>) result.get("shops");
        Long total = MapUtils.getLong(result, "total");
        // 关注信息
        Long thisUserId = SecurityUtils.getSubject().isAuthenticated() ? AccountInfo.getUserId() : null;
        if (thisUserId != null && thisUserId != 0) {
            List<BizFollow> follows = bizFollowService.list(new QueryWrapper<BizFollow>().eq("UserId", thisUserId));
            List<Long> followingIds = follows.stream().map(BizFollow::getBusiId).collect(Collectors.toList());
            if (followingIds.size() > 0) {
                shops.forEach(m -> m.put("followed", followingIds.contains(MapUtils.getLong(m, "id"))));
            }
        }
        // end
        return JsonResult.success()
                .data(shops)
                .total(total)
                .build();
    }

    // devops用户列表接口
    @GetMapping("/n/userShop/searchShops")
    public JsonResult searchShops(@RequestParam(required = false) String shopName, @RequestParam(required = false) Integer busiType,
                                  @RequestParam(required = false) Integer markCode, @RequestParam(required = false) String startTime,
                                  @RequestParam(required = false) String endTime) {

        return null;

    }

    /**
     * 水果零售中心
     *
     * @param markCode
     * @param orderBy  1=综合 2=销量 3=价格升序 4=价格降序
     * @param page
     * @return
     */
    @GetMapping("/n/fruits/getRetail")
    public JsonResult getRetail(Integer markCode, Integer orderBy, Page page) {
        List<Map<String, Object>> result;
        if (orderBy == 1) {
            result = infoMarketService.getRetailFruits(markCode, 1, 0, page);
        } else if (orderBy == 2) {
            result = infoMarketService.getRetailFruits(markCode, 2, 2, page);
        } else if (orderBy == 3) {
            result = infoMarketService.getRetailFruits(markCode, 3, 1, page);
        } else {
            result = infoMarketService.getRetailFruits(markCode, 3, 2, page);
        }
        List<Map<String, Object>> finalResult = new ArrayList<>();
        result.forEach(m -> finalResult.add(SpecialMapUtil.lowKey(m)));

        return JsonResult.success()
                .data(finalResult)
                .total(page.getTotal())
                .build();
    }

    // 通用产品查询接口， 可按产品id，市场code，产品名称查询，支持排序
    // orderBy: 1=综合 2=销量 3=价格
    // dir: 1=asc 2=desc
    @GetMapping("/n/product/getByConditions")
    public JsonResult getProducts(@RequestParam(required = false) Long id, @RequestParam(required = false) Integer markCode,
                                  @RequestParam(required = false) Integer busiType,
                                  @RequestParam(required = false) String title,
                                  @RequestParam(required = false) Integer orderBy, Integer dir, Page page) {
        if (id != null)
            return JsonResult.success().data(infoMarketService.getProductById(id)).build();
        else
            return JsonResult.success().data(infoMarketService.getProducts(markCode, busiType, title, orderBy, dir, page)).build();
    }

    // 按id查询店铺，包括果农和各种厂商
    @GetMapping("/n/shop/getShopIndexById")
    public JsonResult getShopIndexById(Long id, Integer busiType) {
        return JsonResult
                .success()
                .data(infoMarketService.getShopIndexById(id, busiType))
                .build();
    }

    @PostMapping("/n/shop/getShopVOsByBusiIds")
    public List<ShopVO> getShopVOsByBusiIds(@RequestBody List<Long> busiIds, @RequestParam("userId") Long userId) {
        List<ShopVO> result = infoMarketService.getShopVOsByBusiIds(busiIds, userId);
        return result;
    }

    @GetMapping("/n/shop/getShopVOsByGivingUserIds")
    public JSONArray getShopVOsByGivingUserIds(@Json List<Long> givingUserIds, Long userId) {
        return new JSONArray(infoMarketService.getShopVOsByGivingUserIds(givingUserIds, userId));
    }

    @GetMapping("/n/market/getMarkCodesByBusiId")
    public List<Integer> getMarkCodesByBusiId(Long busiId, Integer busiType) {
        return infoMarketService.getMarkCodesByBusiId(busiId, busiType);
    }

    /**
     * 更新市场轮播图
     *
     * @param markCode
     * @param marketRotation
     * @return
     */
    @PostMapping("/market/update/rotation")
    public boolean updateMarketRotation(@RequestParam Integer markCode,
                                        @RequestBody List<Map<String, Object>> marketRotation) {
        return infoMarketService.updateMarketRotation(markCode, marketRotation);
    }
}
